package com.androsz.andslr.app;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.mtp.MtpDevice;
import android.mtp.MtpObjectInfo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Gallery;
import android.widget.Toast;

import com.androsz.andslr.Extras;
import com.androsz.andslr.Intents;
import com.androsz.andslr.LibRaw;
import com.androsz.andslr.R;
import com.androsz.andslr.app.widget.RotatingGalleryScrollView;
import com.androsz.andslr.app.widget.ZoomableImageView;

public class PtpDevicesFragment extends AnalyticFragment {

	private UsbManager usbManager;
	private List<MtpDevice> ptpDevices;

	private RotatingGalleryScrollView refreshGallery() {
		final Activity activity = this.getActivity();

		final RotatingGalleryScrollView container = (RotatingGalleryScrollView) activity
				.findViewById(R.id.ptp_scroll);

		container.setButtons(this, ptpDevices);
		
		return container;
	}

	@Override
	public void onActivityCreated(final Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setHasOptionsMenu(true);

		usbManager = (UsbManager) getActivity().getSystemService(
				Context.USB_SERVICE);

		ptpDevices = new ArrayList<MtpDevice>(2);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		final Activity activity = this.getActivity();
		final RotatingGalleryScrollView container = (RotatingGalleryScrollView) activity
				.findViewById(R.id.ptp_scroll);
		container.refreshDimensions();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		final View view = inflater.inflate(R.layout.fragment_ptp, container);

		//Bitmap thumbnailBitmap = LibRaw.unpackThumbnailBitmapToFit("/sdcard/raw.CR2", (short)512, (short)512);
		//((ZoomableImageView)view.findViewById(R.id.zoomableImageView1)).setBitmap(thumbnailBitmap);
		return view;
	}

	@Override
	public void onPause() {
		super.onPause();
		Activity a = getActivity();

		a.unregisterReceiver(broadcastReceiver);

		clearPtpDevices();
	}

	String mCurFilter;

	@Override
	public void onResume() {
		super.onResume();
		Activity a = getActivity();

		clearPtpDevices();

		// check for existing devices
		for (UsbDevice device : usbManager.getDeviceList().values()) {
			addPtpDevice(device);
		}

		IntentFilter filter = new IntentFilter();
		filter.addAction(Intents.OPEN_PTP_DEVICE);
		filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
		a.registerReceiver(broadcastReceiver, filter);
	}

	private void clearPtpDevices() {
		for (MtpDevice ptpDevice : ptpDevices) {
			ptpDevice.close();
		}
		ptpDevices.clear();
		refreshGallery();
	}

	// searches for a PTP interface on the given USB device
	private static boolean hasPtpInterface(UsbDevice device) {
		int count = device.getInterfaceCount();
		for (int i = 0; i < count; i++) {
			UsbInterface intf = device.getInterface(i);
			if (intf.getInterfaceClass() == 6
					&& intf.getInterfaceSubclass() == 1
					&& intf.getInterfaceProtocol() == 1) {
				return true;
			}
		}
		return false;
	}

	private void addPtpDevice(UsbDevice device) {
		if (device != null) {
			if (hasPtpInterface(device)) {
				UsbDeviceConnection connection = usbManager.openDevice(device);
				if (connection != null) {
					MtpDevice ptpDevice = new MtpDevice(device);
					ptpDevice.open(connection);
					ptpDevices.add(ptpDevice);
					refreshGallery();
				} else {
					trackEvent(String.format(
							"addPtpDevice null connection: %s",
							device.getProductId()), 0);
				}
			} else {
				trackEvent(String.format("addPtpDevice !hasPtpInterface: %s",
						device.getProductId()), 0);
			}
		} else {
			trackEvent("addPtpDevice null device", 0);
		}
	}

	private void removePtpDevice(UsbDevice device) {
		if (device != null) {
			for (MtpDevice ptpDevice : ptpDevices) {
				if (ptpDevice.getDeviceId() == device.getDeviceId()) {
					ptpDevice.close();
					ptpDevices.remove(ptpDevice);
					refreshGallery();
				}
			}
		}
	}

	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (Intents.OPEN_PTP_DEVICE.equals(action)) {
				int ptpDeviceId = intent.getIntExtra(Extras.PTP_DEVICE_ID, 0);
				for (MtpDevice ptpDevice : ptpDevices) {
					if (ptpDevice.getDeviceId() == ptpDeviceId) {
						String s = "";
						for(int id : 
							ptpDevice.getStorageIds())
						{
							int[] handles = ptpDevice.getObjectHandles(id, 0, 0);
							for(int handle : handles)
							{
								MtpObjectInfo mtpoi = ptpDevice.getObjectInfo(handle);
								//CR2 = 45315
								//JFIF
								//byte[] object = ptpDevice.getObject(handle, objectSize);
								s= s+mtpoi.getName() + " ";
							}
						}
						Toast.makeText(context, s, Toast.LENGTH_LONG).show();
						/*Fragment ptpDeviceFragment = new PtpDeviceFragment(
								ptpDevice);
						FragmentTransaction ft = getFragmentManager()
								.beginTransaction();
						ft.setCustomAnimations(android.R.anim.slide_in_left,
								android.R.anim.slide_out_right);

						ft.add(R.id.ptp_container, ptpDeviceFragment,
								"ptpDeviceFragment");
						// Start the animated transition.
						ft.commit();*/
					}
				}
			} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
				UsbDevice device = intent
						.getParcelableExtra(UsbManager.EXTRA_DEVICE);
				removePtpDevice(device);
			}
		}
	};

	@Override
	public void onClick(View v) {		
	}
}